<template>
  <div>
    <crumb :isShowBack="true" />
    <div class="main">
      <div class="main-left">
        <div class="top" style="padding-bottom:30px;height:50px;">
          <div class="left">任务名称：{{resource_training_name}}</div>
          <div class="right" @click="instructions" style="cursor:pointer;"><i class="el-icon-question cursor"></i></div>
        </div>
        <!-- 文本 展示类型 1：文本；2：图片；3：音频；4：视频"-->
        <el-collapse v-model="activeNames">
          <el-collapse-item :name="i"  v-for="(item,i) in titleList" :key="i">
            <div class="resourceTrainingContentEn" v-if="item.displayType==='1'">
              <span>{{item.resourceTrainingContentEn}}</span>
            </div>
            <!-- 图片 -->
            <div class="media-box" v-if="item.displayType === '2'">
              <img :src="item.fileUrl" style="width:100%">
            </div>
            <!-- 音频 -->
            <div class="media-box" v-if="item.displayType === '3'" >
              <audio class="audio" controls :src="item.fileUrl" controlsList="nodownload"></audio>
            </div>
            <!-- 视频 -->
            <div class="media-box" v-if="item.displayType === '4'">
              <video class="video" controls :src="item.fileUrl" controlsList="nodownload">
              </video>
            </div>
          </el-collapse-item>
        </el-collapse>
        <!-- 答题卡 -->
        <div class="answer">
          <div class="quesTitle">答题卡</div>
          <div class="questionBtn">
            <div class="qBtn cursor" v-for="(item, i) in sheet" :key="i" :class="{active:currentTopicIndex===i,isAnswer: item.stu_answer || item.stu_answer === false || item.right_answer.filter(el => { return el.stu_answer }).length>0}" @click="toggleTopic(i)">
              <span>
                {{ i+1 }}
              </span>
            </div>
          </div>
        </div>
      </div>
      <div class="main-right">
        <div class="question-top">
          <span>题量：</span>
          <span class="now-index">{{ currentTopicIndex + 1 }}</span>
          <span class="total">/{{ subjectList.length }}</span>
          <span class="time">耗时:{{timing}}</span>
        </div>
        <!-- 题目内容 -->
        <div class="topic">
          <div>
            <div class="question-title" v-if="topic.subject_content" v-html="'【'+ topic.sort_index + '】' + topic.subject_content"></div>
            <!-- 图片 -->
            <div class="media-box" v-if="topic.display_type === '2'">
              <img :src="topic.file_url" style="width:100%">
            </div>
            <!-- 音频 -->
            <div class="media-box" v-if="topic.display_type === '3'">
              <audio class="audio" controls :src="topic.file_url" controlsList="nodownload"></audio>
            </div>
            <!-- 视频 -->
            <div class="media-box" v-if="topic.display_type === '4'">
              <video class="video" controls :src="topic.file_url">
              </video>
            </div>
            <div v-for="(item, i) in topic.options" :key="i">
              <div class="item cursor" v-if="topic.subject_type!=='14'&&topic.subject_type!=='17'" :class="{ active: sheet[currentTopicIndex].stu_answer === item.num || item.checked}" @click="choiceSheet(item)">
                <span class="chooseBtn cursor" >{{item.num}}</span>
                <span class="question-content" v-if="topic.subject_type==='13'" >
                  <input type="text" v-model="sheet[currentTopicIndex].right_answer[i].stu_answer" @blur="inputSheet(i, $event.target.value)">
                </span>
                <span class="question-content" v-if="topic.subject_type==='10'">
                  {{ item.stu_answer }}
                </span>
                <span class="question-content" v-if="topic.subject_type==='11'">
                  {{ item.stu_answer }}
                </span>
                <span class="question-content" v-if="topic.subject_type==='12'">
                  {{ item.stu_answer }}
                </span>
              </div>
              <div class="item cursor" v-else>
                  <textarea v-model="sheet[currentTopicIndex].right_answer[i].stu_answer" :rows="topic.subject_type==='14'?4:10" @blur="inputSheet(i, $event.target.value)"></textarea>
              </div>
            </div>
            <!-- <div class="item cursor" @click="addResult('B')" :class="{ active: 'B' === showTopicData.result }">
              <span class="chooseBtn cursor"
                ref="b" >B</span>
              <span class="question-content">
                <input type="text" v-model="showTopicData.content[1].content">
              </span>
            </div>
            <div class="item cursor" @click="addResult('C')" :class="{ active: 'C' === showTopicData.result }">
              <span class="chooseBtn cursor" ref="c" >C</span
              >
              <span class="question-content">
                {{ showTopicData.content[2].content }}
              </span>
            </div>
            <div class="item cursor" @click="addResult('D')" :class="{ active: 'D' === showTopicData.result }">
              <span class="chooseBtn cursor" ref="d">D</span>
              <span class="question-content">
                {{ showTopicData.content[3].content }}
              </span>
            </div> -->
            <!-- <div class="item cursor" >
              <textarea placeholder="请输入翻译的答案" rows="4"></textarea>
            </div> -->
          </div>
        </div>
        <!-- 底部按钮 -->
        <div class="controller">
          <div>
            <el-button :disabled="currentTopicIndex === 0" @click="jumpPage(-1)">上一题</el-button>
            <el-button :disabled="currentTopicIndex === sheet.length - 1" @click="jumpPage(1)" >下一题</el-button>
          </div>
          <div>
            <el-button type="primary" class="submit" @click="submit()" @click.stop>提交</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import 'video.js/dist/video-js.css'
import { Practice } from './../practiceApi.js'

export default {
  data () {
    return {
      activeNames: 0,
      lessonTrainingId: '', // 实践任务批次id
      subjectList: [], // 题目列表
      resource_training_name: '', // 任务名称
      checkMessage: '', // 任务说明
      titleList: '', // 题干
      timing: '00:00',
      // 当前题目的索引
      currentTopicIndex: 0,
      topic: {
        file_url: '',
        display_type: '',
        sort_index: '', // 第几题
        subject_id: '', // 题目id
        subject_content: '', // 题目内容
        subject_type: 10, // 题目类型
        itemList: [], // 选项
        options: [] // 题目配置项
      },
      sheet: [], // 答题卡
      setTime: 0,
      updateTime: 0
    }
  },
  methods: {
    inputSheet (i, val) { // 填空题录入
      let score = 100 / this.sheet.length
      this.sheet[this.currentTopicIndex].right_answer[i].right_flag = val === this.sheet[this.currentTopicIndex].right_answer[i].right_answer ? 1 : 0
      this.sheet[this.currentTopicIndex].score = 0
      this.sheet[this.currentTopicIndex].right_answer.forEach(el => {
        if (el.right_flag === 1) {
          this.sheet[this.currentTopicIndex].score += score / this.sheet[this.currentTopicIndex].right_answer.length
        }
      })
    },
    choiceSheet (item) { // 选择题选入
      let score = 100 / this.sheet.length
      if (this.topic.subject_type === '13') {
        return
      }
      if (this.topic.subject_type === '11') {
        item.checked = !item.checked
        this.sheet[this.currentTopicIndex].stu_answer = this.topic.options.filter(el => {
          return el.checked
        }).map(el => {
          return el.num
        }).join(',')
        this.sheet[this.currentTopicIndex].right_flag = item.right_answer === this.sheet[this.currentTopicIndex].stu_answer ? 1 : 0
      } else if (this.topic.subject_type === '12') {
        this.topic.options.forEach(el => {
          if (item.num !== el.num) {
            el.checked = false
          } else {
            item.checked = true
          }
        })
        this.sheet[this.currentTopicIndex].right_flag = item.right_answer === item.stu_answer ? 1 : 0
        this.sheet[this.currentTopicIndex].stu_answer = item.stu_answer
      } else {
        this.sheet[this.currentTopicIndex].right_flag = item.right_answer === item.num ? 1 : 0
        this.sheet[this.currentTopicIndex].stu_answer = item.num
      }
      this.sheet[this.currentTopicIndex].score = this.sheet[this.currentTopicIndex].right_flag === 1 ? score : 0
    },
    // 切换题目
    toggleTopic (index) {
      Practice.updateDuration({
        lessonTrainingId: this.updateTime
      })
      this.currentTopicIndex = index
      this.topic.display_type = this.subjectList[index].display_type
      this.topic.file_url = this.subjectList[index].file_url || ''
      this.topic.sort_index = this.subjectList[index].sort_index
      this.topic.subject_id = this.subjectList[index].subject_id
      this.topic.subject_type = this.subjectList[index].subject_type
      this.topic.subject_content = this.subjectList[index].subject_content
      this.topic.itemList = this.subjectList[index].itemList
      if (this.topic.subject_type === '13') { // 填空题只根据括号‘（’来识别，若接口出现其他形式的数据则失效，此时改接口返回数据或者增加js功能
        this.topic.options = []
        this.topic.options = this.sheet[this.currentTopicIndex].right_answer.map(el => {
          return {
            num: el.answer_code,
            stu_answer: el.stu_answer,
            right_answer: el.right_answer
          }
        })
      } else if (this.topic.subject_type === '10' || this.topic.subject_type === '11') {
        this.topic.options = this.topic.itemList.map(el => {
          return {
            num: el.answer_code,
            stu_answer: el.resource_subject_item_tent,
            right_answer: this.subjectList[index].right_answer,
            checked: false
          }
        })
        if (this.topic.subject_type === '11') {
          this.topic.options = this.topic.options.map(el => {
            el.checked = this.sheet[this.currentTopicIndex].stu_answer.indexOf(el.num) > -1
            return el
          })
        }
      } else if (this.topic.subject_type === '12') {
        this.topic.options = this.topic.itemList.map((el, i) => {
          return {
            num: ['A', 'B'][i],
            stu_answer: el.resource_subject_item_tent,
            right_answer: this.subjectList[index].right_answer,
            checked: this.sheet[this.currentTopicIndex].stu_answer === el.resource_subject_item_tent
          }
        })
      } else {
        this.topic.options = [
          { stu_answer: this.sheet[this.currentTopicIndex].stu_answer || '', right_answer: this.subjectList[index].right_answer }
        ]
      }
      // console.log(this.topic.options)
    },
    // 点击按钮切换题目
    jumpPage (state) {
      this.currentTopicIndex += state
      this.toggleTopic(this.currentTopicIndex)
    },
    async testStart () { // 训练开始
      let postData = {
        lessonTrainingCatalogId: this.$route.query.lessonTrainingCatalogId,
        resourceTrainingId: this.$route.query.resourceTrainingId
      }
      let res = await Practice.testStart(postData)
      if (res.code !== '200') {
        return this.$message.error(res.message)
      }
      let data = res.data
      this.subjectList = data.subjectList
      this.sheet = data.subjectList.map(item => {
        let answer = []
        if (item.subject_type === '13' || item.subject_type === '14') {
          answer = item.right_answer_list.map(el => {
            return {
              right_flag: 0,
              stu_answer: '',
              answer_code: el.answer_code,
              right_answer: el.right_answer
            }
          })
        }
        return {
          subject_id: item.subject_id, // 题目id
          subject_type: item.subject_type, // 题目类型
          stu_answer: '', // 学生作答
          right_answer: answer,
          score: 0, // 分数
          right_flag: 0,
          sort_index: item.sort_index // 题目对应的排序号
        }
      })
      this.resource_training_name = this.$route.query.resource_training_name
      this.checkMessage = data.trainingRemark || '无' // 任务说明
      this.titleList = data.titleList
      this.toggleTopic(0)
      // 计时开始
      let time = 0
      clearInterval(this.setTime)
      this.setTime = setInterval(() => {
        time++
        if (time < 60) {
          this.timing = time < 10 ? '00:0' + time : '00:' + time
        } else if (time < 3600) {
          this.timing = Math.floor(time / 60) < 10 ? '0' + Math.floor(time / 60) + ':' + (time % 60 < 10 ? '0' + time % 60 : time % 60) : Math.floor(time / 60) + ':' + (time % 60 < 10 ? '0' + time % 60 : time % 60)
        } else {
          // this.$alert('答题超时，确定后将自动提交', '超时', {
          //   confirmButtonText: '确定'
          // })
          clearInterval(this.setTime)
        }
      }, 1000)
      // 计时end
      this.lessonTrainingId = data.lessonTrainingId
      // 更新计时？
      Practice.updateDuration({
        lessonTrainingId: data.lessonTrainingId
      })
      // clearInterval(this.updateTime)
      this.updateTime = data.lessonTrainingId
      Practice.updateDuration({
        lessonTrainingId: this.updateTime
      })
    },
    instructions () { // 任务说明
      this.$alert(this.checkMessage, '任务说明', {
        confirmButtonText: '知道了'
      })
    },
    submit () { // 提交训练
      Practice.updateDuration({
        lessonTrainingId: this.updateTime
      })
      let scoreAll = 0
      this.sheet = this.sheet.map(el => {
        scoreAll += el.score
        return el
      })
      scoreAll = scoreAll.toFixed(2)
      scoreAll = Number(scoreAll)
      let unAnswer = this.sheet.filter(el => {
        let isTrue = false
        if (el.right_answer) {
          isTrue = el.right_answer.filter(ele => { return ele.stu_answer === '' }).length > 0
          delete el.stu_answer
        }
        return el.stu_answer === '' || isTrue
      })
      let alertMsg = unAnswer.length !== 0 ? '您还有题目未完成是否确定提交？' : '确定提交本次实践？'
      this.$confirm(alertMsg, '提交', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        Practice.updateDuration({
          lessonTrainingId: this.updateTime
        })
        let res = await Practice.submit({
          id: this.lessonTrainingId,
          resultJson: JSON.stringify(this.sheet),
          score: scoreAll
        })
        if (res.code === '200') {
          clearInterval(this.updateTime)
          clearInterval(this.setTime)
          this.$router.push({ name: 'skillreport', query: { resourceTrainingId: this.$route.query.resourceTrainingId, lessonTrainingCatalogId: this.$route.query.lessonTrainingCatalogId, lessonTrainingId: this.lessonTrainingId } })
        } else {
          this.$message.error(res.message)
        }
      }).then(async () => {
      })
    }
  },
  mounted () {
    this.testStart()
  }
}
</script>

<style scoped lang="scss">
.active {
  background: rgba(7, 118, 182, 1);
}
.main {
  width: 1200px;margin: 0 auto;
  .main-left {
    width: 432px;height: 700px;overflow: hidden;float: left;background: rgba(255, 255, 255, 1);border: 1px solid rgba(229, 229, 229, 1);box-sizing: border-box;padding: 10px;border-radius: 5px;overflow: auto;
    .audio{
      width: 100%;outline:none
    }
    .video{
      width: 100%;outline:none
    }
    .resourceTrainingContentEn{
      padding: 10px;line-height: 1.75;white-space: pre-wrap;text-align: justify;
    }
    .top {
      box-sizing: border-box;padding: 16px 12px;
      .left {
        float: left;font-size: 16px;font-weight: bold;color: #101d37  ;
      }
      .right {
        float: right;font-size: 12px;font-weight: 500;color: #91959a;
        }
    }
    .answer{
      padding: 20px 10px;border-top: solid 1px #eaeaea;margin-top: 20px
    }
    .quesTitle {
      height: 36px;font-size: 16px;font-weight: 500;color: #101d37;padding: 10px;
    }
    .questionBtn {
      display: flex;width: 100%;flex-wrap: wrap;padding: 10px;
      .qBtn {
        color: #91959a;width: calc(20% - 20px);height: 0;text-align: center;margin: 10px;position: relative;padding-bottom: calc(20% - 20px);
        span{
          position: absolute;top: 0;left: 0;width: 100%;height: 100%;border-radius: 3px;display: block;border: 1px solid #91959a;display: flex;align-items: center;justify-content: center;font-size: 18px;
        }
      }
      .qBtn.active span{
        color: #009cf6;border-color: #009cf6;background-color: #fff;border-radius: 3px;
      }
      .qBtn.isAnswer span{
        background-color: #F2F6FC;
      }
      .qBtn:hover span{
        background-color: #EBEEF5;
      }
    }
  }
  .main-right {
    width: calc(100% - 432px - 10px);height: 700px;background: rgba(255, 255, 255, 1);border: 1px solid rgba(229, 229, 229, 1);border-radius: 5px;float: right;padding:10px;position: relative;
    .topic{
      padding: 10px 20px;max-height: 500px;overflow: auto;
    }
    // 右侧题目选择
    .question-top {
      height: 50px;border-bottom: 1px solid #e5e5e5;line-height: 50px;color: #91959a;
      .now-index,.total {
        color: #f86f33;
      }
      .now-index {
        font-size: 26px;
      }
      .total {
        font-size: 16px;
      }
      .time {
        float: right;font-size: 14px;color: #101d37
      }
    }
    .question-title {
      margin: 40px 0 30px;font-size: 16px;color: #101d37;line-height: 2;white-space:pre-wrap
    }
    .item {
      display: flex;border-radius: 3px;align-items: center;margin-bottom: 20px;font-size: 16px;line-height: 2;padding: 0 20px;
      .question-content {
        margin-left: 10px;font-size: 16px;
        input{
          height: 36px;padding: 0 10px;border: none;border-bottom: solid 1px #91959a;outline: none;
        }
      }
      // 右侧的按钮
      .chooseBtn {
        color: #101d37;width: 36px;height: 36px;background: #fff;text-align: center;line-height: 38px;border-bottom: 1px solid #91959a;display: block;
      }
      textarea{
        width: 100%;padding: 10px;line-height: 1.75;outline: none;font-size: 16px;border-radius: 3px;border:solid 1px #91959a; resize:none;
      }
    }
    .item:hover {
      background: #EBEEF5
    }
    .item.active {
      background: #72B6FF;color: #fff
    }
    .item.active .chooseBtn{
      border-color: #72B6FF;color: #72B6FF;
    }
    .item.active .question-content input{
      border-color: #72B6FF;color: #72B6FF;
    }
    // 底部控制按钮
    .controller {
      display: flex;position: absolute;left: 0;bottom: 0;padding: 40px;width: 100%;justify-content: space-between;
    }
  }
}
::v-deep .video-js .vjs-big-play-button {
  position: absolute;transform: translate(-50%, -50%);left: 50%;top: 50%;
}
</style>
